package jianzhioffer;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class LengthOfLongestSubstring {


    public static void main(String[] args) {
        lengthOfLongestSubstring("pwwkew");
    }

    public static int lengthOfLongestSubstring(String s) {
        if (s.length() <= 1) {
            return s.length();
        }
        int res = 1;
        HashSet<Character> window = new HashSet<>();
        int left = 0, right = 0;
        while (right < s.length()) {
            // left指针需要一步一步的移动到重复元素
            while (window.contains(s.charAt(right))) {
                window.remove(s.charAt(left));
                left++;

            }
            window.add(s.charAt(right));
            res = Math.max(res, right - left + 1);
            right++;
        }
        return res;
    }


    // 优化，一步定位到left指针需要到达的位置
    public static int lengthOfLongestSubstring2(String s) {
        if (s.length() <= 1) {
            return s.length();
        }
        int res = 1;
        HashMap<Character, Integer> window = new HashMap<>();
        int left = 0, right = 0;
        while (right < s.length()) {
            int value = window.getOrDefault(s.charAt(right), -1);
            left = Math.max(value + 1, left);
            window.put(s.charAt(right), right);
            res = Math.max(res, right - left + 1);
            right++;
        }

        return res;
    }
}
